﻿#include "facelogin.h"
#include "ui_facelogin.h"

FaceLogin::FaceLogin(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FaceLogin),
    OK(this),
    NO(this)
{
    ui->setupUi(this);
    //statusRes = true;
    statusRes = false;
    errorFace = 0;
    //隐藏标题栏
    this->setWindowFlags(Qt::FramelessWindowHint);

    //read only
    ui->checkBoxResult->setDisabled(true);
    ui->lineEditCardNum->setReadOnly(true);
    ui->lineEditCard->setReadOnly(true);
    ui->lineEditAddress->setReadOnly(true);
    ui->lineEditName->setReadOnly(true);
    ui->lineEditPhone->setReadOnly(true);
    ui->lineEditSex->setReadOnly(true);

    //消息框
    NO.setWindowTitle("提示");
    NO.setText("人脸检测失败！请再次尝试或更换ID");
    NO.addButton("重试",QMessageBox::AcceptRole);

    OK.setWindowTitle("提示");
    OK.setText("人脸检测通过！点击进入系统");
    OK.addButton("进入",QMessageBox::AcceptRole);
}

FaceLogin::~FaceLogin()
{
    delete ui;
    qDebug("facelogin");
}

void FaceLogin::showUserInfo()
{
    qDebug() << UserInfo.size();
    ui->lineEditCardNum->setText(UserInfo["id"]);
    ui->lineEditCard->setText("身份证");
    ui->lineEditAddress->setText(UserInfo["address"]);
    ui->lineEditName->setText(UserInfo["name"]);
    ui->lineEditPhone->setText(UserInfo["nation"]); //phone -> 民族
    ui->lineEditSex->setText(UserInfo["sex"]);
}


//隐藏标题框移动
void FaceLogin::mousePressEvent(QMouseEvent *e)
{
    last=e->globalPosition().toPoint();
}

void FaceLogin::mouseMoveEvent(QMouseEvent *e)
{
    int dx = e->globalPosition().toPoint().x() - last.x();
    int dy = e->globalPosition().toPoint().y() - last.y();
    last = e->globalPosition().toPoint();
    move(x()+dx, y()+dy);
}

void FaceLogin::mouseReleaseEvent(QMouseEvent *e)
{
    int dx = e->globalPosition().toPoint().x() - last.x();
    int dy = e->globalPosition().toPoint().y() - last.y();
    move(x()+dx, y()+dy);
}

//回退
void FaceLogin::on_pushButtonBack_clicked()
{
    emit FacetoLogin();
}

//检测人脸
void FaceLogin::on_pushButtonCheck_clicked()
{
    //功能整合 cap
    if (!allTools::getCap()->isOpened())
    {
        allTools::getCap()->open(0);
        if(!allTools::getCap()->isOpened()) qDebug() << "Can not open a camera\n";
    }
    Mat img;
    QImage _img, __img;
    cv::Mat imgDB = cv::imread(UserInfo["imagePath"].toStdString()); //数据库人脸 user_t
    int times = 0;
    int _times = 0;
    float res = 0;
    while (true)
    {
        *allTools::getCap() >> img;
        if (img.empty()) break;
        cv::flip(img, img, 1);
        cvtColor(img, img, cv::COLOR_BGR2RGB);
        _img  = QImage((const unsigned char*)img.data, img.cols, img.rows, img.step, QImage::Format_RGB888);
        __img = _img.scaled(ui->labelCamera->width(),ui->labelCamera->height());
        ui->labelCamera->setPixmap(QPixmap::fromImage(__img));

        if(allTools::isFaceAntiSpoofingStatus(img))
        {
            ++ _times;
        }
        if(_times >= 3) //YES
        {
            _times = 0;
            errorFace ++;
            if(errorFace == 1)
            {
                QMessageBox t(this);
                t.setWindowTitle("提示");
                t.setText("请勿使用假体！第二次后会记录日志");
                t.addButton("确定",QMessageBox::AcceptRole);
                if(t.exec() == QMessageBox::AcceptRole) {}
            }
            else if(errorFace >= 2)
            {
                errorFace = 0;
                // insert log_t func
                QDate tt = QDate::currentDate();
                //std::string tt_toQstring = tt.toString("yyyy.MM.dd");
                allTools::insertLogInfo(tt.toString("yyyy.MM.dd"), UserInfo["id"], "恶意假体攻击", "192.168.0.1");

                QMessageBox t(this);
                t.setWindowTitle("提示");
                t.setText("已经记录恶意攻击！");
                t.addButton("确定",QMessageBox::AcceptRole);
                if(t.exec() == QMessageBox::AcceptRole) {}
            }
            ui->labelCamera->clear();
            break;
        }
        else  //不是假体
        {
            res = allTools::getFaceCmp(imgDB, img);
            if(times == 10 && res >= allTools::FACE_CMP_THRESHOLD)
            {
                qDebug() << res;
                statusRes = true;
                break;
            }
            else if(times == 30) //30 for wait
            {
                break;
            }
            times ++;
        }

        cv::waitKey(0);
    }

    if(statusRes)
    {
        ui->checkBoxResult->setChecked(true);
        ui->labelResult->setText("检测成功！正在登录...");
        ui->labelCamera->clear();
        statusRes = false;
        if(OK.exec() == QMessageBox::AcceptRole)
        {
            ui->checkBoxResult->setChecked(false);
            ui->labelResult->setText("检测中,请稍后......");
            emit FacetoMainFunc(this->UserInfo); //to mainFunc
        }

    }
    else
    {
        ui->labelCamera->clear();
        if(NO.exec())
        {
            //again
        }
    }
}

